package com.lemon.smartsafety.ui.activity.nine;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatRadioButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TableRow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.common.AreaSelectEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.NineSmallServices;
import com.lemon.smartsafety.listener.AreaType;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.activity.common.AreaProvinceActivity;
import com.lemon.smartsafety.ui.activity.common.IndustryActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.common.ValidateUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/9.
 */
public class NineSmallPropActivity extends SwipeBackActivity {


    @Bind(R.id.metUnitName)
    MaterialEditText     metUnitName;
    @Bind(R.id.metUnitCode)
    MaterialEditText     metUnitCode;
    @Bind(R.id.metLegalPerson)
    MaterialEditText     metLegalPerson;
    @Bind(R.id.metLegalPhone)
    MaterialEditText     metLegalPhone;
    @Bind(R.id.metLegalCid)
    MaterialEditText     metLegalCid;
    @Bind(R.id.metArea)
    MaterialEditText     metArea;
    @Bind(R.id.rowArea)
    TableRow             rowArea;
    @Bind(R.id.metIndustry)
    MaterialEditText     metIndustry;
    @Bind(R.id.rowIndustry)
    TableRow             rowIndustry;
    @Bind(R.id.metUserName)
    MaterialEditText     metUserName;
    @Bind(R.id.metLoginName)
    MaterialEditText     metLoginName;
    @Bind(R.id.radioMale)
    AppCompatRadioButton radioMale;
    @Bind(R.id.radioFemale)
    AppCompatRadioButton radioFemale;
    @Bind(R.id.metPassword)
    MaterialEditText     metPassword;
    @Bind(R.id.metConfirmPassword)
    MaterialEditText     metConfirmPassword;
    @Bind(R.id.metMobile)
    MaterialEditText     metMobile;
    @Bind(R.id.btn_submit)
    Button               btnSubmit;
    private LoggerHelper loggerHelper = new LoggerHelper(NineSmallPropActivity.class);


    private SelectDataI mIndustry;

    private SelectDataI mAreaProvince, mAreaCity, mAreaDistrict, mAreaStreet, mAreaVillage;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
    }


    @Override
    protected void initTitle() {
        setBarTitle("九小场所");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(NineSmallPropActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_nine_small_prop;
    }

    @Override
    protected void initViews() {
        super.initViews();

        metIndustry.setTag("");

    }

    @OnClick({R.id.btn_submit})
    public void submitAction(View view) {
        if (!validateForm()) {
            return;
        }
        getConfirmDialog("是否提交？", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doSubmitAction();
                }
            }
        }).show();

    }

    /**
     * 保存新的机构信息
     */
    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams();

        params.put("company_name", metUnitName.getText().toString().trim());
        params.put("company_code", metUnitCode.getText().toString().trim());
        params.put("legal_person", metLegalPerson.getText().toString().trim());
        params.put("legal_person_phone", metLegalPhone.getText().toString().trim());
        params.put("legal_person_cid", metLegalCid.getText().toString().trim());
        params.put("industry_type_id", mIndustry.getValue());
        params.put("login_name", metLoginName.getText().toString().trim());
        params.put("user_name", metUserName.getText().toString().trim());
        String sex = "0";
        if (radioFemale.isChecked()) {
            sex = "1";
        }
        params.put("sex", sex);
        params.put("login_password", metPassword.getText().toString().trim());
        params.put("mobile", metMobile.getText().toString().trim());


        if (mAreaProvince != null) {
            params.put("selPositionProvinceId", mAreaProvince.getValue(), Field.TYPE_STRING);
        }
        if (mAreaCity != null) {
            params.put("selPositionCityId", mAreaCity.getValue(), Field.TYPE_STRING);
        }
        if (mAreaDistrict != null) {
            params.put("selPositionDistrictId", mAreaDistrict.getValue(), Field.TYPE_STRING);
        }
        if (mAreaStreet != null) {
            params.put("selPositionStreetsId", mAreaStreet.getValue(), Field.TYPE_STRING);
        }
        if (mAreaVillage != null) {
            params.put("selPositionVillageId", mAreaVillage.getValue(), Field.TYPE_STRING);
        }

        NineSmallServices.init().saveNineSmallInfoAction(params);
    }


    private boolean validateForm() {

        if (TextUtils.isEmpty(metUnitName.getText().toString().trim())) {
            metUnitName.setError("请填写单位名称");
            mHUDUtil.showErrorTip(metUnitName.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metUnitCode.getText().toString().trim())) {
            metUnitCode.setError("请填写机构代码");
            mHUDUtil.showErrorTip(metUnitCode.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metLegalPerson.getText().toString().trim())) {
            metLegalPerson.setError("请填写法人名称");
            mHUDUtil.showErrorTip(metLegalPerson.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metLegalPhone.getText().toString().trim())) {
            metLegalPhone.setError("请填写法人电话");
            mHUDUtil.showErrorTip(metLegalPhone.getError().toString());
            return false;
        }


        if (!TextUtils.isEmpty(metLegalCid.getText().toString().trim()) && !ValidateUtils.isCid(metLegalCid.getText()
                                                                                                           .toString()
                                                                                                           .trim())) {
            metLegalCid.setError("身份证号码不合法");
            mHUDUtil.showErrorTip(metLegalCid.getError().toString());
            return false;
        }

        if (mAreaCity == null) {//限制必须要选择到市
            mHUDUtil.showErrorTip("请选择市区");
            return false;
        }

        if (TextUtils.isEmpty(metArea.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择属地");
            return false;
        }



        if (TextUtils.isEmpty(metIndustry.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择行业");
            return false;
        }


        if (TextUtils.isEmpty(metUserName.getText().toString().trim())) {
            metUserName.setError("请填写姓名");
            mHUDUtil.showErrorTip(metUserName.getError().toString());
            return false;
        }
        if (TextUtils.isEmpty(metLoginName.getText().toString().trim())) {
            metLoginName.setError("请填写登录名");
            mHUDUtil.showErrorTip(metLoginName.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metPassword.getText().toString().trim())) {
            metPassword.setError("请填写登录密码");
            mHUDUtil.showErrorTip(metPassword.getError().toString());
            return false;
        }


        String sPassword        = metPassword.getText().toString();
        String sConfirmPassword = metConfirmPassword.getText().toString();
        if (!sPassword.equals(sConfirmPassword)) {
            mHUDUtil.showErrorTip("两次密码不一致");
            return false;
        }


        if (TextUtils.isEmpty(metMobile.getText().toString().trim())) {
            metMobile.setError("请填写手机");
            mHUDUtil.showErrorTip(metMobile.getError().toString());
            return false;
        }
        String sMobile = metMobile.getText().toString().trim();
        if (!ValidateUtils.isMobile(sMobile)) {
            metMobile.setError("手机号码格式不正确");
            mHUDUtil.showErrorTip(metMobile.getError().toString());
            return false;
        }

        return true;
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_NINE_SMALL_ACTION.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            if (!mSharedPreferencesHelper.isLogin()) {
                                mSharedPreferencesHelper.loginOut();
                                mSharedPreferencesHelper.setLoginName(metLoginName.getText().toString().trim());
                                mSharedPreferencesHelper.setLoginPassword(metPassword.getText().toString());
                            }
                            AppManager.getAppManager().finishActivity(NineSmallPropActivity.class);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @OnClick({R.id.metArea, R.id.rowArea, R.id.rowIndustry, R.id.metIndustry})
    public void onClick(View view) {
        if (view.getId() == R.id.metArea || view.getId() == R.id.rowArea) {//地域选择
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_FOR_REGISTER, false);
            UIHelper.showActivity(NineSmallPropActivity.this, bundle, AreaProvinceActivity.class);
        } else if (view.getId() == R.id.rowIndustry || view.getId() == R.id.metIndustry) {//行业
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_MULTI_SELECT, false);
            if (null != mIndustry) {
                bundle.putSerializable(BundleKey.OLD_SELECT_VALUE, StringUtils.nullValue(mIndustry.getValue()));
            }
            UIHelper.showActivity(this, bundle, IndustryActivity.class);

        }
    }


    @Subscribe
    public void onEventMainThread(AreaSelectEvent event) {
        if (AreaType.PROVINCE == event.getType()) {
            mAreaProvince = event.getData();
        } else if (AreaType.CITY == event.getType()) {
            mAreaCity = event.getData();
        } else if (AreaType.DISTRICT == event.getType()) {
            mAreaDistrict = event.getData();
        } else if (AreaType.STREET == event.getType()) {
            mAreaStreet = event.getData();
        } else if (AreaType.VILLAGE == event.getType()) {
            mAreaVillage = event.getData();
        }
        metArea.setText(getAreaViewValue());
    }

    private String getAreaViewValue() {
        StringBuilder sb = new StringBuilder();
        if (mAreaProvince != null) {
            String title = StringUtils.nullValue(mAreaProvince.getTitle());
            sb.append(title);
        } else {
            return sb.toString();
        }
        if (mAreaCity != null) {
            String title = StringUtils.nullValue(mAreaCity.getTitle());
            sb.append("-" + title);
        } else {
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        if (mAreaDistrict != null) {
            String title = StringUtils.nullValue(mAreaDistrict.getTitle());
            sb.append("-" + title);
        } else {
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaStreet != null) {
            String title = StringUtils.nullValue(mAreaStreet.getTitle());
            sb.append("-" + title);
        } else {
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaVillage != null) {
            String title = StringUtils.nullValue(mAreaVillage.getTitle());
            sb.append("-" + title);
        } else {
            mAreaVillage = null;
        }

        return sb.toString();
    }


    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        if (event.getTag().equals(EventTag.TAG_INDUSTRY)) {
            mIndustry = event.getData();
            metIndustry.setText(mIndustry.getTitle());
            metIndustry.setTag(StringUtils.nullValue(mIndustry.getValue()));
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}